app.controller('dangerCtrl', function($rootScope, $scope, httpService, $timeout, $localStorage, toaster,wtmapService){
    $scope.searchParams = {};
    $scope.searchParams.label="上报时间";
    $scope.dangerleyerid="dangerlry";
    $scope.count=0;

    $scope.DangerStatus = wtSys.Emun.DangerStatus; //设施状态
    $scope.MissionLevel = wtSys.Emun.MissionLevel; //紧急程度
    $scope.MissionStatus = wtSys.Emun.MissionStatus; //任务状态
    $scope.searchList = [{
        "typeId" : 1,
        "typeName" : "状态",
        "typeList" : [{"Id" : 0, "Name" : "未处理","checked":true},
            {"Id" : 1, "Name" : "处理中","checked":true}, {
                "Id" : 2,
                "Name" : "已处理"
            }
        ],
        // "isRadio" : true,
    }];
    $scope.searchModel=[{"Id":"0","Name":"未处理","type":"1"},{"Id":"1","Name":"处理中","type":"1"}];
    //地图多点选择
    $scope.setLocationOption = {
        mapid : "setLocation",
        // X: 88501.48813299998 Y: 148552.402262
        center : {x : 88501.48813299998, y : 148552.402262, lng : 0, lat : 0},
        //center : {x : 155307.451, y : 139762.144, lng : 0, lat : 0},
        zoom : 0,
        height : 600,
        showgdmap : false,
        layers : [{layerName : "隐患点", layerFilter : "unitid=" + $localStorage.userInfo.unitid}]
    };


    //二级CAD地图加载  使用Intialed回调是为了保证地图id已绑定值
    $scope.mapcadIntialed = function(scope){

        var promise = wtmapService.intialMap('map2', false, 0, $rootScope.arcgisConfig.lods); //同步调用，获取承诺接口
        promise.then(function(mapobj){

            $scope.mapcadObj = mapobj;


            //$scope.mapcadObj.zoomTobyXY(114307.451, 145762.144, 2);


            //初始化获取隐患列表
            $scope.getDangerList(); //获取隐患列表



        }, function(data){
            //调用承诺接口reject();
        });
    };



    /*==============设置选择设施位置信息 Begin=============================*/

    //设置选择设施位置信息
    $scope.isShowGetPosition = false;
    /**
     * 打开 选择设位置panel
     */
    $scope.openSetPositionPanel = function(){
        $scope.isShowGetPosition = true;
    }
    /**
     * 关闭 选择设位置panel
     */
    $scope.closeGetPositionPanel = function(){
        $scope.isShowGetPosition = false;
        // 获取被选中的点的数据
        $scope.dangerModel.Lng = $scope.selectedPosition.x;
        $scope.dangerModel.Lat = $scope.selectedPosition.y;

    }

    $scope.getPositionOption = {
        mapid : "getPosition",
        center : {x :112655.58913899996, y : 150845.51311699994, lng : 0, lat : 0},
        // center : {x : 155307.451, y : 139762.144, lng : 0, lat : 0},
        zoom : 0,
        height : 600,
        showgdmap : false
    };
    //Edit状态默认被选中的点坐标
    $scope.selectedPosition = {x : 0, y : 0};
    /*==============设置选择设施位置信息 End=============================*/

    // 初始化查询变量
    $scope.initParam = function(){
        $scope.dangerList = [];
        $scope.page = 1;
        $scope.busy = false;
        $scope.limit = 10;
        $scope.isGetDetailTag = true; //第一次默认加载第一条记录右侧信息
    }
    $scope.edit = function(item, index){
        // 还原表单以及表单值
        $scope.dangerForm.$setPristine();
        if(item && (item.Id || item.Id == 0)){
            if(item.DangerStatus != 0){
                return
            }
            $scope.dangerId = item.Id;
            $scope.index = index;
            $scope.editModalTitle = "修改隐患";
            $scope.getDangerDetail($scope.dangerId);
        } else {
            $scope.dangerId = null;
            $scope.index = null;
            $scope.dangerModel = {
                "Name" : "",
                "Code" : "",
                "Note" : "",
                "Lat" : 0,
                "Lng" : 0,
                "Addr" : "",
                "Contact" : "",
                "Phone" : "",
                "DangerType" : "",
                "DeviceId" : "",
                "MissionLevel" : null,
                "HandlerName" : "",
                "HandlerId" : "",
                "Imgs" : []
            }
            $scope.editModalTitle = "新增隐患";
        }
        $('#editModal').modal('show');
    };
    //隐患表单提交
    $scope.dangerFormSubmit = function(){
        $scope.dangerForm.$invalid = true;
        var path = "/danger";
        var type = "POST";
        if($scope.dangerId){
            path = "/danger/" + $scope.dangerId;
            type = "PUT";
        }
        httpService.request(type, path, $scope.dangerModel, function(result){
            $scope.dangerForm.$invalid = false;
            toaster.pop("success", "提示", result.message);
            $('#editModal').modal('hide');
            // 更新列表数据
            var arr = $scope.dangerList;
            if($scope.index != null && $scope.index >= 0){
                arr[$scope.index] = result.data; //index存在直接更新
                $scope.dangerDetailModel = angular.copy($scope.dangerModel);
            } else {
                arr.unshift(result.data);
                $scope.activeId = result.data.Id;
            }
            $scope.dangerList = arr;
        })
    }
    //删除隐患弹框处理
    $scope.del = function(item, index){
        $scope.index = index;
        $scope.delModel = angular.copy(item);
        $('#delModal').modal('show');
    };
    //确认删除隐患
    $scope.delConfirm = function(){
        $('#delModal').modal('hide');
        var path = '/danger/' + $scope.delModel.Id;
        httpService.request("DELETE", path, null, function(result){
            toaster.pop("success", "提示", result.message);
            // 更新列表数据
            var arr = $scope.dangerList;
            arr.splice($scope.index, 1);
            $scope.dangerList = arr;
            //如果删除的是第一条数据,删除成功后重新设置activeId的值
            if($scope.index == 0){
                $scope.activeId = arr[0] ? arr[0].Id : null;
            }
        });
    }
    //消除隐患
    $scope.cancelDanger = function(item){
        if(item.DangerStatus == 2)
            return
        var path = '/danger/cancel/' + item.Id;
        httpService.request("PUT", path, null, function(result){
            toaster.pop("success", "提示", result.message);
            item.DangerStatus = 2;
        });
    }
    //派发任务弹框处理
    $scope.mission = function(item){
        if(item.DangerStatus != 0)
            return
        // 还原表单以及表单值
        $scope.missionForm.$setPristine();
        $scope.missionModel = {
            "Id" : item.Id,
            "MissionLevel" : null,
            "HandlerName" : "",
            "HandlerId" : null,
            "Note" : ""
        };
        $('#missionModal').modal('show');
        $scope.editModel = item;//保存所点击的结构
    };
    //确认派发任务
    $scope.missionFormSubmit = function(){
        $scope.missionForm.$invalid = false;
        $('#missionModal').modal('hide');
        var path = '/Danger/push/' + $scope.missionModel.Id;
        httpService.request("PUT", path, $scope.missionModel, function(result){
            $scope.missionForm.$invalid = false;
            toaster.pop("success", "提示", result.message);
            $scope.editModel.DangerStatus = 1;
            $scope.dangerDetailModel.ServicingCode = result.data.id;
        });
    }
    //获取隐患列表
    $scope.getDangerList = function(isSearch){
        if(isSearch){
            $scope.initParam();
        }
        if($scope.busy) return false;
        var dangerstatus = "";
        var dangertype = ""
        var key = $scope.key ? $scope.key : "";
        if($scope.searchModel){
            var arr = $scope.searchModel;
            if(arr.length > 0){
                var dangerstatusArr = [];
                var dangertypeArr = [];
                arr.forEach(function(item, index){
                    if(item.type == 1){
                        dangerstatusArr.push(item.Id);
                    } else {
                        dangertypeArr.push(item.Id);
                    }
                });
                dangerstatus = dangerstatusArr.join(",");
                dangertype = dangertypeArr.join(",");
            }
        }
        var begintime = $scope.searchParams.begintime;
        begintime = begintime ? moment(begintime).format("YYYY-MM-DD") : "";
        var endtime = $scope.searchParams.endtime;
        endtime = endtime ? moment(endtime).format("YYYY-MM-DD") : "";

        var path = '/danger?page=' + $scope.page + '&limit=' + $scope.limit + '&filter=key:' + key + ";dangerstatus:" + dangerstatus + ";dangertype:" + dangertype + ";begintime:" + begintime + ";endtime:" + endtime;
        $scope.busy = true;
        httpService.request("GET", path, null, function(result){
            $scope.count=result.count;

            //如果是过虑查询，清掉之前的地图数据
            if(isSearch)
                $scope.mapcadObj.drawApi.clearGraphics($scope.dangerleyerid);

            angular.forEach(result.data, function(data, i){
                $scope.dangerList.push(data);

                //绘制隐患图标
                $scope.drawDanger(data);

            });
            if(result.data.length >= $scope.limit){
                $scope.busy = false;
                $scope.page += 1;
            }
            //搜索结果为空 将activeId置为空
            if($scope.dangerList.length == 0){
                $scope.activeId = null;
                return
            }
            if($scope.dangerList.length > 0 && $scope.isGetDetailTag){
                $scope.isGetDetailTag = false;
                var arr = $scope.dangerList;
                $scope.activeId = arr[0].Id; //默认查询第一条记录的详情
            }
        });

    }
    //获取用户列表
    $scope.getUserList = function(){
        var path = '/user?page=1';
        httpService.request("GET", path, null, function(result){
            $scope.userList = result.data;
        });
    }
    //展示维修任务概况详情
    $scope.detail = function(detailId){
        $('#detailModal').modal('show');
        $scope.getServicingDetail(detailId);
    }
    //获取右侧详细信息
    $scope.getDangerDetail = function(Id, isRgt){
        var path = "/danger/" + Id;
        httpService.request("GET", path, null, function(result){

            if(isRgt){
                $scope.dangerDetailModel = result.data;
                if($scope.dangerDetailModel.ServicingCode){
                    $scope.getServicingDetail($scope.dangerDetailModel.ServicingCode);
                }
            } else {
                $scope.dangerModel = result.data;
            };
            //定位
            $scope.mapcadObj.setMapExtendByPoints([{x:result.data.Lng,y:result.data.Lat}], 2,$scope.centerOptions);

        });
    }
    //获取任务详情
    $scope.getServicingDetail = function(Id){
        var path = '/servicing/' + Id;
        httpService.request("GET", path, null, function(result){
            $scope.servicingDetailModel = result.data;
        });
    }
    //获取隐患类型
    $scope.getDangerType = function(){
        var path = '/dangertype';
        httpService.request("GET", path, null, function(result){
            var arr = [];
            if(result.data && result.data.length > 0){

                _.forEach(result.data, function(item){
                    arr.push({"Id" : item.Name, "Name" : item.Name});
                });
                $scope.dangerTypeList = arr;
                $scope.searchList.push({
                    "typeId" : 2,
                    "typeName" : "类型",
                    "typeList" : $scope.dangerTypeList,
                    isRadio : true
                });
            }
        });
    }
    //获取右侧model
    $scope.getRgtModel = function(){
        if(!$scope.activeId){
            return
        }
        $scope.getDangerDetail($scope.activeId, true); //获取隐患详情
    }

    //绘制隐患图标
    $scope.drawDanger=function(dataitem){

        var img="/assets/img/Icons/待处理32.png";
        switch(dataitem.DangerStatus)
        {
            case 0:
                img="/assets/img/Icons/待处理32.png";
                break;
            case 1:
                img="/assets/img/Icons/处理中32.png";
                break;
            case 2:
                img="/assets/img/Icons/已处理32.png";
                break;
        }

        var optionData = {
            "layerid" : $scope.dangerleyerid,
            "symbolUrl" : img,
            "symbolStyle" : {"height" : 32, "width" : 32, "angle" : 0,xOffset : 0,
                yOffset : 16},
            "attributes" : dataitem
        };
        $scope.mapcadObj.drawApi.drawPoint(dataitem.Lng, dataitem.Lat, optionData);

        if(!$scope.dangerLayer)
        {
            $scope.dangerLayer=$scope.mapcadObj.appMap.getLayer($scope.dangerleyerid);
            $scope.dangerLayer.on("click", function(e){
                $scope.rightDataLocation(e.graphic.attributes);
            } );
        }

    }

    //点击图标定位左边数据
    $scope.rightDataLocation=function(dataItem){

        $scope.setCurrent(dataItem.Id);
        $scope.mapcadObj.drawApi.clearGraphics("multilyerid");
        $scope.mapcadObj.drawApi.drawPoint(dataItem.Lng,dataItem.Lat,$scope.centerOptions)
    };

    $scope.setCurrent=function(id){
        $scope.activeId=id;
        $('.data-list').find('li').removeClass("active");//移除之前点击选中的class:active
        var activeEle=$('.data-list').find('li[relativeId="'+$scope.activeId+'"]');
        activeEle.addClass("active");

        $('.lft-wrap').scrollTop(0);
        var top=activeEle.position().top;


        $('.lft-wrap').scrollTop(top);

    }

    $scope.initParam(); // 初始化查询列表变量
    $scope.getUserList(); //获取用户列表

    $scope.getDangerType(); //获取隐患类型


});
